﻿using System;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using App.Core.DataAccess;
using App.Core.Domain;
using System.Threading;
using System.Security.Claims;

namespace App
{
    public class CurrentSession
    {
        private static volatile CurrentSession instance = null;
        private static object lockHelper = new object();

        public static CurrentSession GetInstance()
        {
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null)
                    {
                        instance = new CurrentSession();
                    }
                }
            }

            return instance;
        }

        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid? UserId {
            get
            {
                var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
                if (claimsPrincipal == null)
                {
                    return null;
                }

                var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
                if (claimsIdentity == null)
                {
                    return null;
                }

                var userIdClaim = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value))
                {
                    return null;
                }

                Guid userId;
                if (!Guid.TryParse(userIdClaim.Value, out userId))
                {
                    return null;
                }

                return userId;
            }
        }

        /// <summary>
        /// 是否已登录
        /// </summary>
        public bool IsLogin {
            get {
                return UserId.HasValue;
            }
        }
    }
}